<?php

function xml2array($xml, $i = 0) {
	$array = array();
	if ( $i == 0 ) {
		preg_match_all('/<root>(.*?)<\/root>/ims', $xml, $matches);
		if ( $matches[1] ) {
			$array = xml2array($matches[1][0], $array, ++$i);
		}
	} else {
		if ( ! preg_match_all('/<([a-z]+)>(.*?)<\/\\1>/ims', $xml, $mathces) ) {
			return $xml;
		} else {
			$counts = array();
			foreach ( $mathces[1] as $key => $value ) { 
				$counts[$value][] = $mathces[2][$key];
			}
			foreach ( $counts as $key => $value ) {
				if ( count($value) > 1 ) {
					foreach ( $value as $v ) {
						$array[$key][] = xml2array($v, ++$i);
					}
				} else {
					$array[$key] = xml2array($value[0], ++$i);
				}
			}
		}
	}
	return $array;
}

function check_perm_prompt($type, $key='', $except='') {
	if ( ! check_perm($type, $key,$except) ) {
		prompt(__('对不起，你没有权限执行这项操作。'));
	}
}

//解析主题信息文件
function parse_theme_info($file) {
	$fp = fopen($file, 'rb');
	$content = fread($fp, filesize($file));
	preg_match('/<name>(.+?)<\/name>/is',$content, $name);
	preg_match('/<author>(.*?)<\/author>/is',$content, $author);
	preg_match('/<version>(.*?)<\/version>/is',$content, $version);
	preg_match('/<pubdate>(.*?)<\/pubdate>/is',$content, $pubdate);
	preg_match('/<homepage>(.*?)<\/homepage>/is',$content, $homepage);
	preg_match('/<thumb>(.*?)<\/thumb>/is',$content, $thumb);
	preg_match('/<intro>(.*?)<\/intro>/is',$content, $intro);
	$info = array(
		'name' => $name[1],
		'author' => $author[1],
		'version' => $version[1],
		'pubdate' => $pubdate[1],
		'homepage' => $homepage[1],
		'thumb' => $thumb[1],
		'intro' => $intro[1],
	);
	return $info;
}

//解析插件信息
function parse_plugin_info($file) {
	$content = file_get_contents($file);
	$info = array();
	if ( preg_match('/\/\*(.*?)\*\//sm', $content, $matches) ) {
		$matches = $matches[1];
		preg_match('/PluginName:(.*)/im', $matches, $name);
		preg_match('/PluginUrl:(.*)/im', $matches, $url);
		preg_match('/PluginAuthor:(.*)/im', $matches, $author);
		preg_match('/PluginAuthorUrl:(.*)/im', $matches, $authorurl);
		preg_match('/PluginDesc:(.*)/im', $matches, $desc);
		preg_match('/PluginVer:(.*)/im', $matches, $ver);
		$info['name'] = $name[1];
		$info['url'] = $url[1];
		$info['author'] = $author[1];
		$info['authorurl'] = $authorurl[1];
		$info['description'] = $desc[1];
		$info['version'] = $ver[1];
	}
	return $info;
}

//返回后台模板文件路径
function admin_tpl($file){
	$file = ADMIN_ROOT."template/{$file}.php";
	if ( !file_exists($file) ) {
		die("template ".basename($file)." not exist!");
	}
	return $file;
}

//分类下拉菜单
function cate_options($type, $selid=0, $deep=0) {
	global $db;
	$wheresql = '';
	if ( $deep == 1 ) {
		$wheresql = ' AND parentid = 0';
	}
	$sql = "SELECT id,parentid,children,catename,`count`,orderid FROM ".tname('cate')." WHERE `type` = '$type' $wheresql ORDER BY parentid,orderid";
	$query = $db->query($sql);
	$parents = $children = array();
	while ( $row = $db->fetch_array($query) ) {
		if ( ! $row['parentid'] ) {
			$parents[] = $row;
		} else {
			$row['catename'] = '&nbsp;&nbsp;&nbsp;&nbsp;|-'.$row['catename'];
			$children[$row['parentid']][] = $row;
		}
	}
	$output = '';
	foreach ( $parents as $row ) {
		$selstr = $row['id'] == $selid ? ' selected="selected"' : '';
		if ( $row['children'] ) {
			$selstr .= ' class="parent_option"';
		}
		$output .= '<option value="'.$row['id'].'"'.$selstr.'>'.$row['catename'].($row['children']?'':'('.$row['count'].')').'</option>';
		if ( isset($children[$row['id']]) ) {
			foreach ( $children[$row['id']] as $child ) {
				$selstr = $child['id'] == $selid ? ' selected="selected"' : '';
				$output .= '<option value="'.$child['id'].'"'.$selstr.'>'.$child['catename'].' ('.$child['count'].')</option>';
			}
		}
	}
	return $output;
}

//更新评论统计
function recount_comment($postid) {
	global $db;
	$postid = intval($postid);
	$count = $db->result("SELECT COUNT(*) FROM ".tname('comment')." WHERE postid = '$postid' AND `status` = 1");
	return $db->update('post', array('comments'=>$count), array('id'=>$postid));
}

//加载js
function load_js($array) {
	global $javascript;
	!is_array($array) && $array = array($array);
	foreach ($array as $val) {
		$javascript[] = $val;
	}
}

function prompt($msg,$url='') {
	if ($url) {
		$jumpurl = "window.location='{$url}'";
	} else {
		$jumpurl = "history.back();";
	}
	require admin_tpl('prompt');
	exit();
}

function read_dir($path) {
	if ( substr($path,-1) != '/' ) $path .= '/';
	$result = array('dirs' => array(), 'files' => array());
	if (is_dir($path)) {
		if ($d = opendir($path)) {
			while ( ($file = readdir($d)) !== false ) {
				if ( $file != '.' && $file != '..' ) {
					if ( is_dir($path.$file) ) {
						$result['dirs'][] = $path.$file;
					} elseif ( is_file($path.$file) ) {
						$result['files'][] = $path.$file;
					}
				}
			}
		}
		@closedir($d);
	}
	return $result;
}

function get_statistics() {
	global $_CACHE,$db;
	$db_size = 0;
	$result = $db->query("SHOW TABLE STATUS LIKE '".DB_TABLEPRE."%'");
	while ($table = $db->fetch_array($result)) {
		$db_size += $table['Data_length'] + $table['Index_length'];
	}
	$db_size = $db_size ? sizecount($db_size) : 'unknown';
	$attach_size = $db->result("SELECT SUM(filesize) FROM ".tname('attach')."");
	$attach_size = $attach_size ? sizecount($attach_size) : '0';
	$arcnum = $db->count('post', "`type` = 'blog'");
	$cmtnum = $db->count('comment');
	$usernum = $db->count('user');
	$max_upload = @ini_get('file_uploads') ? ini_get('upload_max_filesize') : 'unknown';
	$register_globals = @ini_get('register_globals') ? 1 : 0;
	$gd_version = function_exists('gd_info') ? (is_array($gd=gd_info()) ? $gd['GD Version'] : '') : 'unknown';

	$statistics = array(
		'db_size' => $db_size,
		'attach_size' => $attach_size,
		'arcnum' => $arcnum,
		'cmtnum' => $cmtnum,
		'usernum' => $usernum,
		'version' => JBLOG_VERSION,
		'release' => JBLOG_RELEASE,
		'server' => $_SERVER['SERVER_SOFTWARE'],
		'php' => PHP_VERSION,
		'mysql' => $db->version(),
		'blogname' => preg_replace('/[\'\"\s]/s', '', $_CACHE['config']['blog']['name']),
		'blogurl' => $_CACHE['config']['blog']['url'],
		'gd_version' => $gd_version,
		'register_globals' => $register_globals,
		'max_upload' => $max_upload,
	);
	$statistics['update'] = rawurlencode(serialize($statistics));
	return $statistics;
}

function multipage ($pagenum = 10) {
	global $count, $pagesize, $page, $url;
	$pagestr = '';
	$url .= strspn('?',$url) ? '&' : '?';
	$realpages = 1;
	if ($count > $pagesize) {
		$realpages = @ceil($count/$pagesize);
		if ($realpages < $pagenum) {
			$from = 1;
			$to = $realpages;
		} else {
			$offset = 5;
			$from = $page - $offset;
			$to = $from + $pagenum;
			if ($from < 1) {
				$from = 1;
				$to = $from + $pagenum - 1;
			} elseif ($to > $realpages) {
				$to = $realpages;
				$from = $realpages - $pagenum + 1;
			}
		}
		$pagestr .= '<span>'.$count.'</span>';
		if ($page > $pagenum) $pagestr .= '<a href="'.$url.'page=1'.'">1...</a>';
		if ($page > 1) $pagestr .= '<a href="'.$url.'page='.($page-1).'">&lsaquo;&lsaquo;</a>';
		for ($i = $from; $i <= $to; $i++) {
			if ($i == $page) {
				$pagestr .= '<span class="on">'.$i.'</span>';
			} else {
				$pagestr .= '<a href="'.$url.'page='.$i.'">'.$i.'</a>';
			}
		}
		if ($page < $realpages) $pagestr .= '<a href="'.$url.'page='.($page+1).'">&rsaquo;&rsaquo;</a>';
		if ($realpages > $to) $pagestr .= '<a href="'.$url.'page='.$realpages.'">'.$realpages.'...</a>';
		if ($realpages > 1 ) $pagestr .= '<input type="text" size="3" class="go" onkeydown="if (event.keyCode==13) {window.location=\''.$url.'page=\'+this.value;return false;}" />';
		$pagestr = '<div class="multipage">'.$pagestr.'</div>';
	}
	return $pagestr;
}
?>